package com.five.admin.server.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.five.admin.dto.AdminEditDto;
import com.five.admin.dto.AdminLoginDto;
import com.five.admin.dto.AllocateDto;
import com.five.admin.mapper.AdminMapper;
import com.five.admin.server.AdminService;
import com.five.admin.server.RoleService;
import com.five.core.exception.CustomerException;
import com.five.core.result.ResultEnum;
import com.five.core.utils.Md5Utils;
import com.five.pojo.entity.Admin;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    private static final String secret="liutaoshigedashabi";

    private static final String pwd="123456";

    @Resource
    private RoleService roleService;

    @Override
    public String adminLogin(AdminLoginDto adminLoginDto) {
        //准备条件
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.eq(Admin::getUsername, adminLoginDto.getUsername());
        Admin admin = getBaseMapper().selectOne(queryWrapper);
        if (admin != null){
            //加密拿到的密码
            String md5Password = Md5Utils.md5Password(adminLoginDto.getPassword(), admin.getSalt());
            if (md5Password.equals(admin.getPassword())){

                Map<String, Object> tokenMap = new HashMap<>();
                tokenMap.put("username",admin.getUsername());
                tokenMap.put("id",admin.getId());
                tokenMap.put("phone",admin.getPhone());
                tokenMap.put("image",admin.getImage());
                tokenMap.put("exp",System.currentTimeMillis()+1000*60*60*24);
                return JWTUtil.createToken(tokenMap,secret.getBytes(StandardCharsets.UTF_8));
            }
        }
        throw new CustomerException(ResultEnum.PASSWORD_IS_FALSE);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void allocateRoles(AllocateDto allocateDto) {
        //删除该管理员的所有角色
        roleService.deleteRole(allocateDto.getAdminId());
        //添加新的角色
        if (allocateDto.getRoleIds().size()>0){
            getBaseMapper().allocateRoles(allocateDto.getAdminId(),allocateDto.getRoleIds());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean addAdmin(AdminEditDto adminEditDto) {
        Admin admin = AdminEditDto2Admin(adminEditDto);
        //设置初始密码以及盐
        String salt = Md5Utils.createSalt();
        String password = Md5Utils.md5Password(pwd, salt);
        admin.setSalt(salt);
        admin.setPassword(password);
        int inserted = getBaseMapper().insert(admin);
        if (inserted>0){
            //添加角色
            if (!adminEditDto.getRoleIds().isEmpty()) {
                getBaseMapper().allocateRoles(admin.getId(), adminEditDto.getRoleIds());
            }
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public void updateAdmin(AdminEditDto adminEditDto) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminEditDto,admin);

        roleService.deleteRole(adminEditDto.getId());

        int updated = getBaseMapper().updateById(admin);
        if (adminEditDto.getRoleIds().isEmpty()){
            return;
        }
        getBaseMapper().allocateRoles(admin.getId(),adminEditDto.getRoleIds());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean deleteAdmin(Long id) {
        int deleted = getBaseMapper().deleteById(id);
        if (deleted>0){
            roleService.deleteRole(id);
            return true;
        }
        return false;
    }

    /**
     * 转化成Admin
     * @param adminEditDto
     * @return
     */
    private Admin AdminEditDto2Admin(AdminEditDto adminEditDto){
        return Admin.builder()
                .id(adminEditDto.getId())
                .name(adminEditDto.getName())
                .username(adminEditDto.getUsername())
                .phone(adminEditDto.getPhone())
                .email(adminEditDto.getEmail())
                .image(adminEditDto.getAvatar())
                .build();
    }
}
